package com.easybbs.component;

import com.easybbs.constants.Constants;
import com.easybbs.entity.enums.CheckCodeTypeEnum;
import com.easybbs.entity.vo.response.AccountCheckCodeRspVO;
import com.easybbs.redis.RedisUtils;
import com.easybbs.utils.StringTools;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @Author: yudaxian
 * @Description: redis 方法
 * @DateTime: 2024/10/18 10:36
 **/
@Component("redisComponent")
public class RedisComponent {

    @Resource
    private RedisUtils redisUtils;

    public AccountCheckCodeRspVO saveCheckCode(String checkCode, CheckCodeTypeEnum checkCodeTypeEnum) {
        String checkCodeKey = UUID.randomUUID().toString();
        if (checkCodeTypeEnum.equals(CheckCodeTypeEnum.LOGIN_REGISTER)) {
            redisUtils.setex(Constants.LOGIN_REGISTER_REDIS_KEY + checkCodeKey, checkCode, Constants.REDIS_EXPIRE_TIME);
        } else {
            redisUtils.setex(Constants.EMAIL_CHECKCODE_REDIS_KEY + checkCodeKey, checkCode, Constants.REDIS_EXPIRE_TIME);
        }
        AccountCheckCodeRspVO accountCheckCodeRspVO = AccountCheckCodeRspVO.builder()
                .checkCodeKey(checkCodeKey)
                .codeType(checkCodeTypeEnum.getCode())
                .build();
        return accountCheckCodeRspVO;
    }

    public Boolean checkCheckCode(String checkCode, String checkCodeKey, CheckCodeTypeEnum checkCodeTypeEnum) {
        String redisCheckCode = null;
        if (checkCodeTypeEnum.equals(CheckCodeTypeEnum.LOGIN_REGISTER)) {
            redisCheckCode = (String) redisUtils.get(Constants.LOGIN_REGISTER_REDIS_KEY + checkCodeKey);
        } else {
            redisCheckCode = (String) redisUtils.get(Constants.EMAIL_CHECKCODE_REDIS_KEY + checkCodeKey);
        }
        // 验证码过期或不存在
        if (StringTools.isEmpty(redisCheckCode)) {
            return false;
        }
        // 验证码错误
        if (!redisCheckCode.equals(checkCode)) {
            return false;
        }
        // 验证码正确
        return true;
    }

    public void deleteCheckCode(String checkCodeKey, CheckCodeTypeEnum checkCodeTypeEnum) {
        if (checkCodeTypeEnum.equals(CheckCodeTypeEnum.LOGIN_REGISTER)) {
            redisUtils.delete(Constants.LOGIN_REGISTER_REDIS_KEY + checkCodeKey);
        } else {
            redisUtils.delete(Constants.EMAIL_CHECKCODE_REDIS_KEY + checkCodeKey);
        }
    }
}
